package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysRoleDeptService;
import com.ruoyi.system.service.ISysRoleMenuService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private ISysRoleMenuService roleMenuService;

    @Autowired
    private ISysRoleDeptService roleDeptService;

    @Autowired
    private ISysUserRoleService userRoleService;

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysRole> selectRoleList(SysRole role) {
        MPJLambdaWrapper<SysRole> queryWrapper = new MPJLambdaWrapper<SysRole>()
                .distinct()
                .selectAll(SysRole.class)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysRole::getDelFlag, "0");

        if (StringUtils.isNotNull(role)) {
            // 根据角色名称查询
            if (StringUtils.isNotEmpty(role.getRoleName())) {
                queryWrapper.like(SysRole::getRoleName, role.getRoleName());
            }
            // 根据权限字符串查询
            if (StringUtils.isNotEmpty(role.getRoleKey())) {
                queryWrapper.like(SysRole::getRoleKey, role.getRoleKey());
            }
            // 根据状态查询
            if (StringUtils.isNotEmpty(role.getStatus())) {
                queryWrapper.eq(SysRole::getStatus, role.getStatus());
            }
            // 时间范围查询
            if (StringUtils.isNotNull(role.getParams())) {
                Map<String, Object> params = role.getParams();
                if (params.get("beginTime") != null) {
                    queryWrapper.ge(SysRole::getCreateTime, params.get("beginTime"));
                }
                if (params.get("endTime") != null) {
                    queryWrapper.le(SysRole::getCreateTime, params.get("endTime"));
                }
            }
        }

        queryWrapper.orderByAsc(SysRole::getRoleSort);
        return roleMapper.selectList(queryWrapper);
    }

    /**
     * 根据用户ID查询角色权限
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    public List<SysRole> selectRolePermissionByUserIdJoin(Long userId) {
        MPJLambdaWrapper<SysRole> queryWrapper = new MPJLambdaWrapper<SysRole>()
                .distinct()
                .selectAll(SysRole.class)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysRole::getDelFlag, "0")
                .eq(SysUserRole::getUserId, userId);

        return roleMapper.selectJoinList(SysRole.class, queryWrapper);
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = selectRolePermissionByUserIdJoin(userId);
        List<SysRole> allRoles = selectRoleAll();

        Set<Long> userRoleIds = userRoles.stream()
                .map(SysRole::getRoleId)
                .collect(Collectors.toSet());

        for (SysRole role : allRoles) {
            if (userRoleIds.contains(role.getRoleId())) {
                role.setFlag(true);
            }
        }
        return allRoles;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRole> perms = selectRolePermissionByUserIdJoin(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery(SysRole.class)
                .eq(SysRole::getDelFlag, "0")
                .orderByAsc(SysRole::getRoleSort);
        return roleMapper.selectList(queryWrapper);
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        MPJLambdaWrapper<SysUserRole> queryWrapper = new MPJLambdaWrapper<SysUserRole>()
                .select(SysUserRole::getRoleId)
                .eq(SysUserRole::getUserId, userId);

        List<SysUserRole> userRoles = userRoleMapper.selectJoinList(SysUserRole.class, queryWrapper);
        return userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
        return roleMapper.selectById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();

        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery(SysRole.class)
                .eq(SysRole::getRoleName, role.getRoleName())
                .eq(SysRole::getDelFlag, "0");
        SysRole info = roleMapper.selectOne(queryWrapper);

        if (StringUtils.isNotNull(info) && !info.getRoleId().equals(roleId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();

        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery(SysRole.class)
                .eq(SysRole::getRoleKey, role.getRoleKey())
                .eq(SysRole::getDelFlag, "0");
        SysRole info = roleMapper.selectOne(queryWrapper);

        if (StringUtils.isNotNull(info) && !info.getRoleId().equals(roleId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleIds 角色id
     */
    @Override
    public void checkRoleDataScope(Long... roleIds) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            for (Long roleId : roleIds) {
                SysRole role = new SysRole();
                role.setRoleId(roleId);
                List<SysRole> roles = SpringUtils.getAopProxy(this).selectRoleList(role);
                if (StringUtils.isEmpty(roles)) {
                    throw new ServiceException("没有权限访问角色数据！");
                }
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getRoleId, roleId);
        return Math.toIntExact(userRoleMapper.selectCount(queryWrapper));
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRole(SysRole role) {
        role.setDelFlag("0");
        int rows = roleMapper.insert(role);
        if (rows > 0 && StringUtils.isNotEmpty(role.getMenuIds())) {
            rows = insertRoleMenu(role);
        }
        return rows;
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(SysRole role) {
        // 修改角色信息
        int rows = roleMapper.updateById(role);
        // 删除角色与菜单关联
        if (rows > 0 && StringUtils.isNotEmpty(role.getMenuIds())) {
            roleMenuService.deleteRoleMenuByRoleId(role.getRoleId());
            rows = insertRoleMenu(role);
        }
        return rows;
    }

    /**
     * 修改角色状态
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(SysRole role) {
        LambdaUpdateWrapper<SysRole> updateWrapper = Wrappers.lambdaUpdate(SysRole.class)
                .eq(SysRole::getRoleId, role.getRoleId())
                .set(SysRole::getStatus, role.getStatus());
        return roleMapper.update(null, updateWrapper);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role) {
        // 修改角色信息
        int rows = roleMapper.updateById(role);
        if (rows > 0 && StringUtils.isNotEmpty(role.getDeptIds())) {
            // 删除角色与部门关联
            roleDeptService.deleteRoleDeptByRoleId(role.getRoleId());
            // 新增角色和部门信息（数据权限）
            rows = insertRoleDept(role);
        }
        return rows;
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuService.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            rows = roleDeptService.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleById(Long roleId) {
        LambdaUpdateWrapper<SysRole> updateWrapper = Wrappers.lambdaUpdate(SysRole.class)
                .eq(SysRole::getRoleId, roleId)
                .set(SysRole::getDelFlag, "2");
        int rows = roleMapper.update(null, updateWrapper);
        if (rows > 0) {
            // 删除角色与菜单关联
            roleMenuService.deleteRoleMenuByRoleId(roleId);
            // 删除角色与部门关联
            roleDeptService.deleteRoleDeptByRoleId(roleId);
        }

        return rows;
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRole(roleId));
            checkRoleDataScope(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }

        LambdaUpdateWrapper<SysRole> updateWrapper = Wrappers.lambdaUpdate(SysRole.class)
                .in(SysRole::getRoleId, Arrays.asList(roleIds))
                .set(SysRole::getDelFlag, "2");

        int rows = roleMapper.update(null, updateWrapper);
        if (rows > 0) {
            // 删除角色与菜单关联
            roleMenuService.deleteRoleMenu(roleIds);
            // 删除角色与部门关联
            roleDeptService.deleteRoleDept(roleIds);
        }
        return rows;
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole) {
        return userRoleService.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        return userRoleService.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleService.batchUserRole(list);
    }
    /**
     * 根据用户ID查询角色
     *
     * @param userName 用户名
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserName(String userName){
        MPJLambdaWrapper<SysRole> queryWrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysRole::getDelFlag, "0")
                .eq(SysUser::getUserName, userName);
        return roleMapper.selectList(queryWrapper);
    }
}
